console.log("开始生成模板文件");
const fs = require("fs");
const path = require("path");
const db = require("../const/dbConst");

// 获取参数
const args = process.argv.splice(2);
const tableName = args[0];
const moduleName = toHump(tableName);
const ModuleName = firstToUpper(moduleName);
let router = "./router/";
let model = "./model/";
let api = "./api/";
let views = "./"+ModuleName+"/";

console.log(
  `table_name:${tableName},小写驼峰：${moduleName},大写驼峰：${ModuleName}`
);

generate_entity();
generate_router();
generate_vue_template_api();
generate_vue_template();

function generate_router(parentPath = "") {
  let root = router;
  const mysql = require("mysql");
  const connection = mysql.createConnection({
    host: db.HOST,
    user: db.USER,
    password: db.PASSWORD,
    database: db.DATABASE,
  });
  connection.connect();
  connection.query(
    `show full columns from \`${tableName}\``,
    function (error, results, fields) {
      if (error) throw error;
      if (results.length == 0) return;
      let targetDirPath = path.join(__dirname, root, parentPath);
      let targetFilePath = path.join(
        __dirname,
        root,
        parentPath,
        moduleName + ".js"
      );
      if (!fs.existsSync(targetDirPath)) {
        fs.mkdirSync(targetDirPath);
        console.log("The " + targetDirPath + " folder has been created!");
      }

      let head = `const express = require("express");
const router = express.Router();
const {success, successWithData} = require("../utils/result")
const { check } = require('express-validator');
const {checkParam}  = require("../utils/checkUtils")
const ${ModuleName} = require("../db/model/${moduleName}Model");`;

      fs.writeFileSync(targetFilePath, head, {
        flag: "a",
      });

      // 分页查询注释
      let pageQueryTest = `\n\n/**
 * 分页查询接口
 * @api {POST} /${moduleName}/query${ModuleName}ListByPage 分页查询接口
 * @apiDescription 分页查询接口
 * @apiName query${ModuleName}ListByPage
 * @apiHeader {String} authorization 用户token,格式：Bearer xxxx
 * @apiBody {Number} page=1   页码
 * @apiBody {Number} limit=10   每页条数
 * @apiParamExample {json} Request-Example:
 *     {
 *        "page": 1,
 *        "limit": "10",
 *     }
 * @apiGroup ${ModuleName}
 * @apiVersion 1.0.0
 */
router.post("/${moduleName}/query${ModuleName}ListByPage", check('page').not().isEmpty(),check('limit').not().isEmpty(), async function (req, res) {
  checkParam(req)
  const { page, limit, type } = req.body;
  const where = {};
  let offset = (page - 1) * limit;
  if (type) {
    where["type"] = type;
  }
  const result = await ${ModuleName}.findAndCountAll({
    limit,
    offset,
    where,
    order: [["created_time", "DESC"]],
  });
  return res.json(successWithData(result));
});`;
      fs.writeFileSync(targetFilePath, pageQueryTest, {
        flag: "a",
      });

      // 添加接口
      let addApi = `\n\n\n/**
 * @api {POST} /${moduleName}/add 添加
 * @apiDescription 添加
 * @apiName add
 * @apiHeader {String} authorization 用户token,格式：Bearer xxxx`;
      fs.writeFileSync(targetFilePath, addApi, {
        flag: "a",
      });
      results.forEach((item) => {
        let fieldName = item["Field"];
        let fieldType = item["Type"];
        let comment = item["Comment"];
        console.log(fieldName, fieldType, comment);
        let typeName = "";
        let line = "";
        if (
          fieldType.indexOf("int") !== -1 ||
          fieldType.indexOf("decimal") !== -1
        ) {
          typeName = "Number";
          line = `\n * @apiBody {${typeName}} ${fieldName}=1   ${comment}`;
        } else if (
          fieldType.indexOf("varchar") !== -1 ||
          fieldType.indexOf("text") !== -1
        ) {
          typeName = "String";
          line = `\n * @apiBody {${typeName}} ${fieldName}='${comment}'   ${comment}`;
        } else if (
          fieldType.indexOf("datetime") !== -1 &&
          (fieldName !== "created_time" || fieldName !== "updated_time")
        ) {
          typeName = "String";
          line = `\n * @apiBody {${typeName}} ${fieldName}='1994-04-01'   ${comment}`;
        }
        fs.writeFileSync(targetFilePath, line, {
          flag: "a",
        });
      });

      let exampleText = `\n * @apiParamExample {json} Request-Example:
 *     {`;
      fs.writeFileSync(targetFilePath, exampleText, {
        flag: "a",
      });

      results.forEach((item) => {
        let fieldName = item["Field"];
        let fieldType = item["Type"];
        let comment = item["Comment"];
        console.log(fieldName, fieldType, comment);
        let typeName = "";
        let line = "";
        if (
          fieldType.indexOf("int") != -1 ||
          fieldType.indexOf("decimal") != -1
        ) {
          typeName = "Number";
          line = `\n *        "${fieldName}": 1,`;
        } else if (
          fieldType.indexOf("varchar") != -1 ||
          fieldType.indexOf("text") != -1
        ) {
          typeName = "String";
          line = `\n *        "${fieldName}": '${comment}',`;
        } else if (
          fieldType.indexOf("datetime") !== -1 &&
          (fieldName !== "created_time" || fieldName !== "updated_time")
        ) {
          typeName = "String";
          line = `\n *        "${fieldName}": '1994-04-01',`;
        }
        fs.writeFileSync(targetFilePath, line, {
          flag: "a",
        });
      });
      let footerText =
        "\n *     }\n" +
        ` * @apiGroup ${ModuleName}\n` +
        " * @apiVersion 1.0.0\n" +
        " */\n";
      fs.writeFileSync(targetFilePath, footerText, {
        flag: "a",
      });

      let addFunText = `router.post("/${moduleName}/add",  async function (req, res) {
  await ${ModuleName}.create({...req.body});
  return res.json(success());
});`;
      fs.writeFileSync(targetFilePath, addFunText, {
        flag: "a",
      });

      // 编辑接口
      let editApi = `\n\n\n/**
 * @api {POST} /${moduleName}/edit 编辑
 * @apiDescription 编辑
 * @apiName edit
 * @apiHeader {String} authorization 用户token,格式：Bearer xxxx`;
      fs.writeFileSync(targetFilePath, editApi, {
        flag: "a",
      });
      results.forEach((item) => {
        let fieldName = item["Field"];
        let fieldType = item["Type"];
        let comment = item["Comment"];
        console.log(fieldName, fieldType, comment);
        let typeName = "";
        let line = "";
        if (
          fieldType.indexOf("int") != -1 ||
          fieldType.indexOf("decimal") != -1
        ) {
          typeName = "Number";
          line = `\n * @apiBody {${typeName}} ${fieldName}=1   ${comment}`;
        } else if (
          fieldType.indexOf("varchar") != -1 ||
          fieldType.indexOf("text") != -1
        ) {
          typeName = "String";
          line = `\n * @apiBody {${typeName}} ${fieldName}='${comment}'   ${comment}`;
        } else if (
          fieldType.indexOf("datetime") !== -1 &&
          (fieldName !== "created_time" || fieldName !== "updated_time")
        ) {
          typeName = "String";
          line = `\n * @apiBody {${typeName}} ${fieldName}='1994-04-01'   ${comment}`;
        }
        fs.writeFileSync(targetFilePath, line, {
          flag: "a",
        });
      });

      let editExampleText = `\n * @apiParamExample {json} Request-Example:
 *     {`;
      fs.writeFileSync(targetFilePath, editExampleText, {
        flag: "a",
      });

      results.forEach((item) => {
        let fieldName = item["Field"];
        let fieldType = item["Type"];
        let comment = item["Comment"];
        console.log(fieldName, fieldType, comment);
        let typeName = "";
        let line = "";
        if (
          (fieldType.indexOf("int") !== -1 ||
            fieldType.indexOf("decimal") !== -1) &&
          fieldName !== "id"
        ) {
          typeName = "Number";
          line = `\n *        "${fieldName}": 1,`;
        } else if (
          fieldType.indexOf("varchar") != -1 ||
          fieldType.indexOf("text") != -1
        ) {
          typeName = "String";
          line = `\n *        "${fieldName}": '${comment}',`;
        } else if (
          fieldType.indexOf("datetime") !== -1 &&
          (fieldName !== "created_time" || fieldName !== "updated_time")
        ) {
          typeName = "String";
          line = `\n *        "${fieldName}": '1994-04-01',`;
        }
        fs.writeFileSync(targetFilePath, line, {
          flag: "a",
        });
      });
      let editFooterText =
        "\n *     }\n" +
        ` * @apiGroup ${ModuleName}\n` +
        " * @apiVersion 1.0.0\n" +
        " */\n";
      fs.writeFileSync(targetFilePath, editFooterText, {
        flag: "a",
      });

      let editFunText = `router.post("/${moduleName}/edit", check('id').not().isEmpty(),async function (req, res) {
  checkParam(req)
  await ${ModuleName}.update({...req.body}, {where: {id:req.body.id}});
  return res.json(success());
});`;
      fs.writeFileSync(targetFilePath, editFunText, {
        flag: "a",
      });

      // 删除接口
      let delText = `\n\n/**
 * @api {POST} /${moduleName}/del 删除
 * @apiDescription 删除
 * @apiName del
 * @apiHeader {String} authorization 用户token,格式：Bearer xxxx
 * @apiBody {Number} id=1   主键id
 * @apiParamExample {json} Request-Example:
 *     {
 *        "id": 1,
 *     }
 * @apiGroup ${ModuleName}
 * @apiVersion 1.0.0
 */
router.post("/${moduleName}/del", check('id').not().isEmpty(),async function (req, res) {
  checkParam(req)
  await ${ModuleName}.destroy({where: {id:req.body.id}});
  return res.json(success());
});
module.exports = router;`;
      fs.writeFileSync(targetFilePath, delText, {
        flag: "a",
      });
    }
  );
}

/**
 * 生成实体Model
 * @param parentPath
 */
function generate_entity(parentPath = "") {
  let root = model;
  const mysql = require("mysql");
  const connection = mysql.createConnection({
    host: db.HOST,
    user: db.USER,
    password: db.PASSWORD,
    database: db.DATABASE,
  });
  connection.connect();
  connection.query(
    `show full columns from \`${tableName}\``,
    function (error, results, fields) {
      if (error) throw error;
      if (results.length === 0) return;
      let targetDirPath = path.join(__dirname, root, parentPath);
      let targetFilePath = path.join(
        __dirname,
        root,
        parentPath,
        moduleName + "Model.js"
      );
      if (!fs.existsSync(targetDirPath)) {
        fs.mkdirSync(targetDirPath);
        console.log("The " + targetDirPath + " folder has been created!");
      }

      let head = `const { DataTypes } = require("sequelize");
const sequelize = require("../../config/sequelize");
const ${ModuleName} = sequelize.define("${tableName}", {\n`;

      fs.writeFileSync(targetFilePath, head, {
        flag: "a",
      });

      results.forEach((item) => {
        let fieldName = item["Field"];
        let fieldType = item["Type"];
        let comment = item["Comment"];
        console.log(fieldName, fieldType, comment);
        let typeName = "";
        if (fieldType.indexOf("int") != -1) {
          typeName = "INTEGER";
        } else if (
          fieldType.indexOf("varchar") != -1 ||
          fieldType.indexOf("text") != -1
        ) {
          typeName = "STRING";
        } else if (fieldType.indexOf("decimal") != -1) {
          typeName = "DECIMAL";
        }
        let line = "";
        if (fieldName !== "created_time" && fieldName !== "updated_time") {
          if (fieldName === "id") {
            line =
              "    /**\n" +
              "     * 主键\n" +
              "    */\n" +
              "    id: {\n" +
              "       type: DataTypes.INTEGER,\n" +
              "       allowNull: false,\n" +
              "       primaryKey: true,\n" +
              "       autoIncrement: true,\n" +
              "    },\n";
          } else {
            line = `    /**
     * ${comment}
     */
    ${fieldName}: {
        type: DataTypes.${typeName},
    },\n`;
          }
          fs.writeFileSync(targetFilePath, line, {
            flag: "a",
          });
        }
      });
      fs.writeFileSync(
        targetFilePath,
        `});
module.exports = ${ModuleName};`,
        {
          flag: "a",
        }
      );
    }
  );
}

/**
 * 生成vue页面模板
 * @param {string} parentPath 
 */
function generate_vue_template(parentPath = ""){
  let root = views;
  // 连接数据库
  const mysql = require("mysql");
  const connection = mysql.createConnection({
    host: db.HOST,
    user: db.USER,
    password: db.PASSWORD,
    database: db.DATABASE,
  });
  connection.connect();
  connection.query(
    `show full columns from \`${tableName}\``,
    function (error, results, fields) {
      if (error) throw error;
      if (results.length == 0) return;
      // 设置保存目录
      let targetDirPath = path.join(__dirname, root, parentPath);
      let targetFilePath = path.join(
        __dirname,
        root,
        parentPath,
        "index.vue"
      );
      if (!fs.existsSync(targetDirPath)) {
        fs.mkdirSync(targetDirPath);
        console.log("The " + targetDirPath + " folder has been created!");
      }
      function write(html){
        fs.writeFileSync(targetFilePath, html, {
          flag: "a",
        });
      }
      // 开始构建模板
      let queryFormTemplate = `<template>
  <!-- 查询栏 -->
  <div class="query">
    <QueryForm :form="form" v-model="queryData" @handleQuery="handleQuery" />
  </div>
  <!-- 表单栏 -->
  <div class="table">
    <BaseTable
      v-loading="tableLoading"
      :columns="columns"
      :data="dataList"
      :pager="pager"
      @handleCurrentChange="handleCurrentChange"
      @handleAction="handleAction"
      highlight-current-row
    >
      <template v-slot:action>
        <el-button type="primary" @click="handleCreate">新增</el-button>
      </template>
    </BaseTable>
    <!-- 弹窗 -->
    <el-dialog
      :title="action == 'add' ? '新增' : '编辑'"
      v-model="showModal"
      :before-close="handleClose"
    >
      <el-form
        ref="dialogForm"
        :rules="rules"
        :model="dataForm"
        label-width="100px"
      >`
      write(queryFormTemplate)

      // *************写入dialog弹窗start*************
      let hasEdit = false
      let hasImg = false
      results.forEach((item) => {
        let fieldName = item["Field"];
        let fieldType = item["Type"];
        let comment = !!item["Comment"] ? item["Comment"] : fieldName;
        let dialogItemTemplate = ""
        // 数字类别
        if(fieldType.indexOf("text") !== -1){
          hasEdit = true
          dialogItemTemplate = `\n        <el-form-item label="${comment}" prop="${fieldName}">
          <editor v-model="dataForm.${fieldName}"></editor>
        </el-form-item>`
        }else if(fieldName.indexOf("img") !== -1){
          hasImg = true
          dialogItemTemplate = `\n        <el-form-item label="${comment}" prop="${fieldName}">
            <UploadImage
              :limit="1"
              v-model="dataForm.${fieldName}"
              @change="validParams('${fieldName}')"
            />
        </el-form-item>`
        }else if(fieldName.indexOf("status") !== -1 && comment && comment.indexOf("#") !== -1){
          // eg: 状态#0-禁用;1-启用
          let commentName = comment.split("#")[0]
          let enum_arr = comment.split("#")[1].split(";")
          dialogItemTemplate = `\n        <el-form-item label="${commentName}" prop="${fieldName}">
          <el-select v-model="dataForm.${fieldName}">`
          if(enum_arr.length > 1){
            for (let index = 0; index < enum_arr.length; index++) {
              const element = enum_arr[index];
              let data = element.split("-")
              dialogItemTemplate += `\n            <el-option :value="${data[0]}" label="${data[1]}"></el-option>`
            }
          }
          dialogItemTemplate += `\n          </el-select>
        </el-form-item>`
        }else if(fieldName != "created_time" && fieldName != "updated_time" && fieldName != "id"){
          dialogItemTemplate = `\n        <el-form-item label="${comment}" prop="${fieldName}">
          <el-input
            v-model="dataForm.${fieldName}"
            placeholder="请输入${comment}"
          />
        </el-form-item>`
        }
        if(dialogItemTemplate !== "")write(dialogItemTemplate)
      })
      write(`\n      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>`)
      // *************写入dialog弹窗 end*************
      
      // *************写入script start*************
      let importTemplate = `\n<script lang="ts" setup>
import { nextTick, onMounted, reactive, ref, toRaw } from "vue";
import {
  query${ModuleName}ListByPage,
  ${moduleName}Add,
  ${moduleName}Edit,
  ${moduleName}Del,
} from "@/api/${moduleName}";
import { ElMessage } from "element-plus";`
      if(hasEdit){
        importTemplate += `\nimport Editor from "@/components/Editor.vue";`
      }
      if(hasImg){
        importTemplate += `\nimport UploadImage from "@/components/UploadImage.vue";`
      }
      importTemplate += `\n/****************************************** data ******************************************/

// 参数
const pager = reactive({
  page: 1,
  limit: 10,
  total: 0,
});
// 渲染数据
const dataList = ref(<any>[]);

// 编辑动作：add,edit,delete
const action = ref("");

// 弹窗变量
const showModal = ref(false);

// 弹窗ref
const dialogForm = ref(<any>null);

// 表单loading
const tableLoading = ref(false);

// 初始化用户表单对象
const queryData = ref(<any>{});`
      write(importTemplate)

      // 表格变量
      let dataTemplate = `\n// 表格提交数据
interface DataModel {`
      write(dataTemplate)

      let handleSubmitTemplate = `let model:DataModel = {`
      results.forEach((item) => {
        let fieldName = item["Field"];
        let fieldType = item["Type"];
        let comment = !!item["Comment"] ? item["Comment"] : fieldName;
        let dataItemTemplate = ""
        if(fieldName == "id"){
          dataItemTemplate = `\n  id?: number, //${comment}`
        }else if(fieldType.indexOf("int") != -1 || fieldType.indexOf("decimal") != -1 ){
          dataItemTemplate = `\n  ${fieldName}: number, //${comment}`
        }else if(fieldType.indexOf("varchar") != -1 || fieldType.indexOf("text") != -1){
          dataItemTemplate = `\n  ${fieldName}: string, //${comment}`
        }else if(fieldName != "created_time" && fieldName != "updated_time"){
          dataItemTemplate = `\n  ${fieldName}: any, //${comment}`
        }
        if(dataItemTemplate != ""){
          if(fieldName != "id"){
            handleSubmitTemplate += `\n        ${fieldName}: params.${fieldName}, //${comment}`
          }
          write(dataItemTemplate)
        }
        
      })
      handleSubmitTemplate += "\n      }"
      write(`\n}
const dataForm = ref(<DataModel>{});`)

      // 开始写入查询时框form
      let formTemplate = `\n\n// 生成查询form结构数据
const form = [`
      write(formTemplate)
      results.forEach((item) => {
        let fieldName = item["Field"];
        let fieldType = item["Type"];
        let comment = !!item["Comment"] ? item["Comment"] : fieldName;
        let dialogItemTemplate = ""
        
        if(fieldName.indexOf("status") !== -1 && comment && comment.indexOf("#") !== -1){
          // eg: 状态#0-禁用;1-启用
          let commentName = comment.split("#")[0]
          let enum_arr = comment.split("#")[1].split(";")
          dialogItemTemplate += `\n {
    type: "select",
    label: "${commentName}",
    model: "${fieldName}",
    placeholder: "请选择${commentName}",
    options: [`
          if(enum_arr.length > 1){
            for (let index = 0; index < enum_arr.length; index++) {
              const element = enum_arr[index];
              let data = element.split("-")
              dialogItemTemplate += `\n      { label: "${data[1]}", value: ${data[0]} },`
            }
          }
          dialogItemTemplate += `\n    ],
  },`
        }else if(fieldName != "created_time" && fieldName != "updated_time"){
          dialogItemTemplate = `\n  {
    type: "input",
    label: "${comment}",
    model: "${fieldName}",
    placeholder: "请输入${comment}",
  },`
        }
        write(dialogItemTemplate)
      })
      write(`\n];`)

      // 定义动态表格的格式
      let columnsTemplate = `\n\n// 定义动态表格的格式\nconst columns = reactive([`
      write(columnsTemplate)
      results.forEach((item) => {
        let fieldName = item["Field"];
        let fieldType = item["Type"];
        let comment = !!item["Comment"] ? item["Comment"] : fieldName;
        let columnsItemTemplate = ""
        if(fieldName.indexOf("status") !== -1 && comment && comment.indexOf("#") !== -1){
          // eg: 状态#0-禁用;1-启用
          let commentName = comment.split("#")[0]
          let enum_arr = comment.split("#")[1].split(";")
          columnsItemTemplate += `\n  {
    type: "tag",
    label: "${commentName}",
    prop: "${fieldName}",
    formatter: (row: any, column: any, value: number) => {
      return {`
          if(enum_arr.length > 1){
            for (let index = 0; index < enum_arr.length; index++) {
              const element = enum_arr[index];
              let data = element.split("-")
              columnsItemTemplate += `\n          ${data[0]}: "${data[1]}",`
            }
          }
          columnsItemTemplate += `\n      }[value];
    },
    dict: {`
          if(enum_arr.length > 1){
            for (let index = 0; index < enum_arr.length; index++) {
              const element = enum_arr[index];
              let data = element.split("-")
              if(data[0] == 0){
                columnsItemTemplate += `\n        ${data[0]}: "danger", `
              }else{
                columnsItemTemplate += `\n        ${data[0]}: "success", `
              }
            }
          }
          columnsItemTemplate += `\n    },
  },`
        }else if(fieldName.indexOf("img") != -1){
          columnsItemTemplate += `\n  {
    type: "img",
    label: "${comment}",
    prop: "${fieldName}",
  },`
        }else{
          columnsItemTemplate += `\n  {
    label: "${comment}",
    prop: "${fieldName}",
  },`
        }
        write(columnsItemTemplate)
      })
      write(`\n {
    type: "action",
    label: "操作",
    width: 140,
    list: [{ text: "编辑", type: "text" }, { text: "删除" }],
  },
]);\n\n`)

      // 弹窗校验规则
      let rulesTemplate = `// 弹窗校验规则\nconst rules = reactive({`
      write(rulesTemplate)
      results.forEach((item) => {
        let fieldName = item["Field"];
        let fieldType = item["Type"];
        let comment = !!item["Comment"] ? item["Comment"] : fieldName;
        let ruleItemTemplate = ""
        if(fieldName.indexOf("img") !== -1){
          ruleItemTemplate += `\n  ${fieldName}: [
    {
      required: true,
      message: "请上传${fieldName}",
      trigger: "change",
    },
  ],`
        }else{
          ruleItemTemplate += `\n  ${fieldName}: [
    {
      required: true,
      message: "请输入${comment}",
      trigger: "blur",
    },
  ],`
        }
        write(ruleItemTemplate)
      })
      write(`\n});
/****************************************** 生命周期函数 ******************************************/
onMounted(() => {
  handleQuery();
});

/****************************************** method ******************************************/
`)
      let methedTemplate = ""
      if(hasImg){
        methedTemplate += `\nconst validParams = (fieldName: String) => {
  dialogForm.value.validateField(fieldName, () => null);
};`
      }
      methedTemplate += `\n// 查询
const handleQuery = async () => {
  tableLoading.value = true;
  let data = (await query${ModuleName}ListByPage({ ...pager, ...queryData.value })).data;
  dataList.value = data.rows;
  pager.total = data.count;
  tableLoading.value = false;
};

// 分页事件处理
const handleCurrentChange = (current: number) => {
  pager.page = current;
  handleQuery();
};

// 新增
const handleCreate = () => {
  action.value = "add";
  showModal.value = true;
};

// 操作
const handleAction = async ({ text, row }: any) => {
  if (text === "编辑") {
    action.value = "edit";
    showModal.value = true;
    await nextTick();
    Object.assign(dataForm.value, row);
  } else if (text === "删除") {
    await ${moduleName}Del({ id: row.id });
    ElMessage({ message: "删除成功", type: "success" });
    handleQuery();
  }
};

// 取消
const handleClose = () => {
  showModal.value = false;
  handleReset(dialogForm);
};

// 重置
const handleReset = (form: any) => {
  form.value.resetFields();
};

// 提交
const handleSubmit = () => {
  let res: any;
  dialogForm.value.validate(async (valid: boolean) => {
    if (valid) {
      let params = toRaw(dataForm.value);
      ${handleSubmitTemplate}
      if (action.value === "add") {
        res = await ${moduleName}Add(params);
      } else if (action.value === "edit") {
        model.id = params.id
        res = await ${moduleName}Edit(params);
      }
      if (res && res.code === 200) {
        showModal.value = false;
        ElMessage({ message: "操作成功", type: "success" });
        handleReset(dialogForm);
        handleQuery();
      }
    }
  });
};
</script>

<style lang="scss" scoped></style>
`
      write(methedTemplate)
      // *************写入script end*************
    }
  )

}

/**
 * 生成vue页面接口-增删改查
 * @param {string} parentPath 
 */
function generate_vue_template_api(parentPath = ""){
  let root = api;
  let targetDirPath = path.join(__dirname, root, parentPath);
  let targetFilePath = path.join(
    __dirname,
    root,
    parentPath,
    moduleName + ".ts"
  );
  if (!fs.existsSync(targetDirPath)) {
    fs.mkdirSync(targetDirPath);
    console.log("The " + targetDirPath + " folder has been created!");
  }

  let apiTemplate = `import request from "../utils/request";\n
export function query${ModuleName}ListByPage(data: any) {
  return request({
    url: "${moduleName}/query${ModuleName}ListByPage",
    method: "post",
    data,
  });
}

export function ${moduleName}Add(data: any){
  return request({
      url: "${moduleName}/add",
      method: "post",
      data,
    });
}

export function ${moduleName}Edit(data: any){
    return request({
        url: "${moduleName}/edit",
        method: "post",
        data,
      });
}

export function ${moduleName}Del(data: any){
    return request({
        url: "${moduleName}/del",
        method: "post",
        data,
      });
}`
  fs.writeFileSync(targetFilePath, apiTemplate, {
    flag: "a",
  });
}

/**
 * 首字母大写
 * @param str
 * @returns {*}
 */
function firstToUpper(str) {
  return str.trim().replace(str[0], str[0].toUpperCase());
}

/**
 * 下划转小驼峰
 * @param name
 * @returns {string}
 */
function toHump(name) {
  let newName = name.toLowerCase();
  let arr = newName.split("");
  for (let index in arr) {
    if (arr[index] == "_") {
      let i = parseInt(index);
      arr[i + 1] = arr[i + 1].toUpperCase();
    }
  }
  return arr.join("").replace(/_/g, "");
}

/**
 * 下划转中横线
 * @param name
 * @returns {string}
 */
function toLine(name) {
  let newName = name.toLowerCase();
  let arr = newName.split("");
  for (let index in arr) {
    if (arr[index] == "_") {
      let i = parseInt(index);
      arr[i + 1] = arr[i + 1];
    }
  }
  return arr.join("").replace(/_/g, "-");
}

/**
 * 退出程序
 */
function exit() {
  setTimeout(() => {
    process.exit(1);
  }, 5000);
}

exit();
